import json
import re
from tokenize import TokenError
from django.http import HttpResponse, JsonResponse
from cryptography.fernet import InvalidToken
from django.shortcuts import render
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ViewSet
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import status
from django.http import JsonResponse
# 导入用户权限登录模块
from rest_framework.permissions import IsAuthenticated
from Admins.models import *
from Admins import serilizers


# 登录视图 重写认证模块实现用户多字段登录
class LoginView(TokenObtainPairView):
    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        try:
            serializer.is_valid(raise_exception=True)
        except TokenError as e:
            raise InvalidToken(e.args[0])
        result_data = serializer.validated_data
        result_data['username'] = serializer.user.username
        result_data['id'] = serializer.user.id
        result_data['email'] = serializer.user.email
        result_data['token'] = result_data.pop('access')
        # result_data['avatar'] = serializer.user.avatar
        return JsonResponse(result_data, status=status.HTTP_200_OK)


def register(request):
    '''注册'''
    # 一、接受用户参数
    body_unicode = request.body.decode('utf-8')
    # 解析JSON数据为Python字典
    data = json.loads(body_unicode)
    username = data.get('username')
    print("username")
    password = data.get('password')
    email = data.get('email')
    password_confirm = data.get('password_confirm')
    print("获取所有信息")
    print(username, password, email, password_confirm)
    # 二、参数校验
    # 1.校验参数是否为空
    if not all([username, password, email, password_confirm]):
        return JsonResponse({'error': "所有参数不能为空"}, status=status.HTTP_400_BAD_REQUEST)
    # 2.校验用户名是否已注册
    if Administrators.objects.filter(username=username).exists():
        return JsonResponse({'error': "用户名已存在"}, status=status.HTTP_400_BAD_REQUEST)
    # 3.校验两次密码是否一致
    if password != password_confirm:
        return JsonResponse({'error': "两次密码不一致"}, status=status.HTTP_400_BAD_REQUEST)
    # 4.校验密码是否过长
    if not (6 <= len(password) <= 18):
        return JsonResponse({'error': "密码长度需要在6到18位之间"}, status=status.HTTP_400_BAD_REQUEST)
    # 5.校验邮箱是否存在
    if Administrators.objects.filter(email=email).exists():
        return JsonResponse({'error': "该邮箱已被其他用户使用"}, status=status.HTTP_400_BAD_REQUEST)
    # 6.校验邮箱格式是否正确
    if not re.match(r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$', email):
        return JsonResponse({'error': "邮箱格式有误！"}, status=status.HTTP_400_BAD_REQUEST)
    print("获取用户上传信息")
    # 三、创建用户
    obj = Administrators.objects.create(username=username, email=email, password=password)
    res = {
        'username': obj.username,
        'id': obj.id,
        'email': obj.email
    }
    return JsonResponse(res, status=status.HTTP_200_OK)

class LogoutView(APIView):
    def get(self, request):
        # 跳转路由
        next_page = ""
        return JsonResponse({'next_page': next_page}, status=status.HTTP_200_OK)